package com.eg.thingscloud.example.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.alibaba.fastjson.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;

public class ApiUtil {

	/**
	 * 
	 * @param accessToken 请求token
	 * @param mainContent 请求业务主体
	 */
	public static void excute(String accessToken, JSONObject mainContent) {
		String timestamp = getTimeStamp();
		String taskResult = post(Constants.THINGSCLOUD_API_URL, accessToken, timestamp, mainContent.toJSONString());
		System.out.println(taskResult);
	}

	/**
	 * 往服务端发送请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param accessToken
	 * @param timestamp
	 *            请求时间
	 * @param paramMainContentStr
	 *            请求业务参数组成的json字符串
	 * @return
	 */
	private static String post(String url, String accessToken, String timestamp, String paramMainContentStr) {
		// 创建一个OkHttpClient对象
		OkHttpClient okHttpClient;
		if(url.contains("https")){
			okHttpClient = new OkHttpClient.Builder().sslSocketFactory(getCertificates()).hostnameVerifier(new HostnameVerifier() {
				public boolean verify(String hostname, SSLSession session) {
					//对于自己生成的签名证书，需要将hostnameVerifier设置成验证结果为true
					return true;
				}
			}).build();
		}else{
			okHttpClient = new OkHttpClient();	
		}

		FormBody.Builder formBuilder = new FormBody.Builder();
		formBuilder.add("timestamp", timestamp);
		formBuilder.add("main_content", paramMainContentStr);
		Builder builder = new Request.Builder();
		builder.url(url);
		builder.addHeader("access_token", accessToken);
		builder.post(formBuilder.build());

		Request request = builder.build();
		// 发送请求获取响应
		try {
			Response response = okHttpClient.newCall(request).execute();
			// 判断请求是否成功
			if (response.isSuccessful()) {
				// 打印服务端返回结果
				// Log.i(TAG,response.body().string());
				return response.body().string();
			} else {
				System.out.println("failed: "+response.body().string());
				return "response failed";
			}
		} catch (IOException e) {
			e.printStackTrace();
			return "io exception";
		}
	}

	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public static String getTimeStamp() {
		LocalDateTime localtDateAndTime = LocalDateTime.now();
		ZonedDateTime dateAndTimeInShanghai = ZonedDateTime.of(localtDateAndTime,
				ZoneId.of(ZoneId.SHORT_IDS.get("CTT")));
		return dateAndTimeInShanghai.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	}
	
	/**
     * 添加https认证
     *
     * @return
     */
    private static SSLSocketFactory getCertificates() {
        try {
        	String baseDir = System.getProperty("user.dir");
            InputStream inputStream = new FileInputStream(new File(baseDir+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"213995005080281.pem"));
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);

            int index = 0;
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(inputStream));

            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
